﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;

namespace Clarius.Silverlight.Streaming.Library.Operations
{
    internal class RetrieveFileListOperation : SilverlightStreamingOperation
    {
        FileSet fileSet;

        internal RetrieveFileListOperation(FileSet fileSet)
        {
            this.fileSet = fileSet;

            base.Initialize(fileSet.Parent);
        }

        protected override void HandleErrorFromHttpStatusCode(System.Net.HttpStatusCode statusCode, string errorText, Exception ex)
        {
            throw new SilverlightStreamingException(errorText, ex);
        }

        protected override WebRequest GetWebRequest()
        {
            HttpWebRequest request;
            request = WebUtil.GetWebRequest(this.accountManager.Account, "/" + fileSet.Name);

            return request;
        }

        protected override object ParseWebResponse(string responseText)
        {
            List<File> files = new List<File>();

            XmlDocument xmlContent = new XmlDocument();
            xmlContent.LoadXml(responseText);
            XmlNodeList fileNodes = xmlContent.GetElementsByTagName("file");
            foreach (XmlNode node in fileNodes)
            {
                string filename = node.Attributes["name"].Value;
                string filesizeString = node.Attributes["size"].Value;
                string mimeType = node.Attributes["mimeType"].Value;
                long filesize;
                long.TryParse(filesizeString, out filesize);
                File file = new File(filename, filesize, mimeType, fileSet);
                files.Add(file);
            }

            return files;
        }
    }
}
